# -*- coding: utf-8 -*-

import requests
from operate_database import insert_or_update_info, select_flow

url = 'http://localhost:8700'


# 上传mrpa⽂件
def upload_mrpa(file_path,rpa_name):
    headers = {
        "Accept": "application/json",
        # 注意：通常不需要手动设置 Content-Type 为 multipart/form-data，
        # 当使用 requests.post() 的 files 参数时，requests 会自动设置正确的 Content-Type。
    }
    files = {
        'mrpa': (rpa_name + '.mrpax', open(file_path, 'rb'),
                 'application/octet-stream')
    }

    # 注意：由于你设置了 Accept 头部为 application/json，服务器应该返回 JSON 响应。
    # 但是，如果服务器实际上返回的是其他类型的内容（比如 HTML 或纯文本），
    # 你可能需要调整响应的处理方式。
    response = requests.post(url + '/mrpa/upload', headers=headers, files=files)

    if response.status_code != 200:
        print('上传错误')
        return response.json()
    else:
        mrpaid = response.json()['mrpa_id']
        mrpa_file_md5 = response.json()['mrpa_file_md5']


def get_local_ip():
    import socket
    # 获取当前系统主机名
    hostname = socket.gethostname()
    # 获取主机名对应的IP地址
    local_ip = socket.gethostbyname(hostname)
    # print(local_ip)
    return local_ip


# 获取已上传mrpa⽂件
def get_process():

    headers = {'Content-Type': 'application/json'}
    res = requests.get(url + '/mrpa/list', headers=headers)
    # print(res.text)
    ip = get_local_ip()
    if res.status_code != 200:
        return False
    else:
        for i in res.json()['mrpa_file_list']:
            # print(i)
            oneinfo = (ip, i['mrpa_id'], i['file_name'], i['file_path'], i['file_md5'])
            sql = f"select * from flow_info where mrpa_id='{i['mrpa_id']}'"
            # print(sql)
            data = select_flow(sql)
            # print(data)
            if data == []:
                sql = r"INSERT INTO flow_info (robot_id, mrpa_id, flow_name, file_path, file_md5) VALUES (?,?,?,?,?)"
                if not insert_or_update_info(sql, oneinfo):
                    print('插入失败')
                else:
                    pass
        return True


# 获取机器人健康状态
def robot_health():
    headers = {'Content-Type': 'application/json'}
    res = requests.get(url + '/executor/healthcheck', headers=headers)
    if res.status_code != 200:
        return False, '请求机器人接口失败'
    else:
        if res.json()['error_code'] != 0:
            return res.json()['error_code'], res.json()['result']
        else:
            return True, '机器人还活着'

'''
# 查询所有历史 GET /executor/history
def get_process_history():
    headers = {'Content-Type': 'application/json'}
    res = requests.get(url + '/executor/history?detailed=true', headers=headers)
    if res.status_code != 200:
        return False
    else:
        for i in res.json()['detailedhistorys']:
            # print(i)
            sql = f"select * from flow_history where workflowid='{i['workflowId']}'"
            # print(sql)
            data = select_flow(sql)
            # print(data)
            if data == []:
                if i['type'] == 'pre-execute':
                    oneinfo = (i['mrpaId'], i['type'], i['workflowId'],  i['startTime'], i['endTime'])
                    sql = r"INSERT INTO flow_history (flow_id, status, workflowid, start_time, stop_time) VALUES (?,?,?,?,?)"
                else:
                    oneinfo = (i['mrpaId'], i['type'], i['workflowId'], i['endTime'])
                    sql = r"INSERT INTO flow_history (flow_id, status, workflowid, stop_time) VALUES (?,?,?,?)"
                if not insert_or_update_info(sql, oneinfo):
                    print('插入失败')
'''




#异步执行流程，参数：mrpaid
def start_async_flow(mrpaid):
    headers = {'Content-Type': 'application/json'}
    res = requests.post(url + '/executor/run/async/' + mrpaid, headers=headers)
    # print(res.json())


# 停止流程，参数workid
def stop_flow(workid):
    headers = {'Content-Type': 'application/json'}
    res = requests.post(url + '/executor/stop/' + workid, headers=headers)
    # print(res.json())


#暂停执行流程
def pause_flow(workid):
    headers = {'Content-Type': 'application/json'}
    res = requests.post(url + '/executor/pause/' + workid, headers=headers)
    # print(res.json())


# 继续执行流程
def continue_flow(workid):
    headers = {'Content-Type': 'application/json'}
    res = requests.post(url + '/executor/continue/' + workid, headers=headers)
    # print(res.json())


if __name__ == '__main__':
    print()
    # print(robot_health())
    # start_async_flow('1730427654421_3fad9029-14d8-40d1-95db-0177eea31996')
    # get_process_history()
    # get_process()
    # upload_mrpa("D:\Cyclone_Setup_5.0.RCSP5\发布包\打印日志.mrpax", '打印日志2')
